package com.bdzl.pub.util.xss;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @创建人 wuwenjie
 * @创建时间 2018/7/22
 * @描述 业务系统
 */
public class HttpRequest {
    /**
     * get请求
     *
     * @param url    请求地址
     * @param params map参数
     * @return json
     */
    public static JSONObject getJsonData(String url, Map<String, String> params) {
        return JSONObject.parseObject(HttpRequest.getJsonDataString(url, params));
    }

    /**
     * get请求
     *
     * @param url    请求地址
     * @param params map参数
     * @return json
     */
    public static String getJsonDataString(String url, Map<String, String> params) {
        // 获取当前客户端对象
        HttpGet request=null;
        try {
            URIBuilder builder = new URIBuilder(url);
            if (params!=null&&!params.isEmpty()){
                List<NameValuePair> pairs = new ArrayList<>();
                params.forEach((K, V) -> pairs.add(new BasicNameValuePair(K, V)));
                builder.setParameters(pairs);
            }
            request = new HttpGet(builder.build());// 根据地址发送get请求
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return HttpRequest.request(request);
    }

    /**
     * post请求
     *
     * @param url    url
     * @param params map
     * @return String
     */
    public static String postJsonDataString(String url, Map<String, String> params) {
        HttpPost httpPost = new HttpPost(url);
        if (params!=null&&!params.isEmpty()) {
            //拼接参数
            List<BasicNameValuePair> pairs = new ArrayList<>();
            params.forEach((K, V) -> pairs.add(new BasicNameValuePair(K, V)));
            httpPost.setEntity(new UrlEncodedFormEntity(pairs, StandardCharsets.UTF_8));
        }
        return HttpRequest.request(httpPost);
    }

    /**
     * post请求
     *
     * @param url    url
     * @param params map
     * @return json
     */
    public static JSONObject postJsonData(String url, Map<String, String> params) {
        return JSONObject.parseObject(HttpRequest.postJsonDataString(url, params));
    }

    public static String sendHttpPost(String url, String body) {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new StringEntity(body, StandardCharsets.UTF_8));
        return HttpRequest.request(httpPost);
    }

    /**
     * @Author Zhn
     * @Description //TODO POST请求from data 传值
     * @Date 17:46 2021/5/20
     * @Param [url, param]
     * @return java.lang.String
     **/
    public static String doPost(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,"utf-8");
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return resultString;
    }




    /**
     * 所有发送Http请求的公共方法
     * @param http     * @return
     */
    private static String request(HttpRequestBase http){
        http.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        try(CloseableHttpClient httpClient = HttpClients.createDefault()) {
            CloseableHttpResponse response = httpClient.execute(http);
            String result=EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            response.close();
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String sendHttpPost(String url, String body,CloseableHttpClient closeableHttpClient) {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new StringEntity(body, StandardCharsets.UTF_8));
        httpPost.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        try(CloseableHttpClient httpClient = closeableHttpClient) {
            CloseableHttpResponse response = httpClient.execute(httpPost);
            String result=EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            response.close();
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static byte[] postBytes(String url, String jsonString){
        try(CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(url);  // 接口
            httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
            StringEntity entity = new StringEntity(jsonString);
            entity.setContentType("image/png");
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);
            return IOUtils.toByteArray(response.getEntity().getContent());
        }catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }
}